<?php
/**
 * Created by PhpStorm.
 * User: 万奇
 * Date: 2020/11/29 0029
 * Time: 23:15
 */

namespace app\admin\controller\v1;

use app\Request;
use think\App;
use think\facade\Db;

use app\core\Wechat;

class Extend extends BasicController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }
    public function get_del_user(){
        $data['id']                    = uuid();
        $data['external_user_id']      = 'wm2KBLHwAAF9j3yFwqtsUpXLmstMr-LA';
        $data['name']                  = "执着";
        $data['avatar']                = "http://wx.qlogo.cn/mmhead/IbQhd2Y9oKefALopwnKCrfTMz2m7ckQbicGVcaXYjNth4Bd0BwcRGRhlnLGRia5dPIOHiamViaLVgzw/0";
        $data['customer_type']         = 1;
        $data['gender']                = 1;
        $data['follow_remark_company'] = '';
        $data['tag_ids']               = 'et2KBLHwAAbT-gMgcH6PUqqhb4qtGZlQ,et2KBLHwAAXl8dzhu-gzW69njwSkzUIw,et2KBLHwAAFabpSDesIpqrv6XVw9-j6A,et2KBLHwAAt_YrKmI8NWrOG9UnCv1VKw';
        $data['follow_userid']         = "wangshuo";
        $data['follow_remark']         = '';
        $data['follow_createtime']     = date('Y-m-d,H:i:s',1739184651);
        $data['follow_remark_mobiles'] = '';
        $data['follow_add_way']        = 1;
        $data['follow_oper_userid']    = 'wm2KBLHwAAF9j3yFwqtsUpXLmstMr-LA';
        $data['follow_state']          = '';
        Db::name('wxk_customer')->insert($data);
    }
    //线索统计
    public function get_leads_count(){
        $admin = $this->user_info;
        $param = $this->param;
        $where = [];
        $where_time = [];
        $sales = Db::name('sys_user')
            ->where('userid','in',['huayunlong','wangshuo','zhangguoqing','dongguoqing'])
            ->column('username,userid');

        if (is_exists($param['start_time']) && is_exists($param['end_time'])) {
            $where_time[] = ['follow_createtime', 'between', [$param['start_time'], $param['end_time']]];
        }else{
            $t_start = date('Y-m-d 00:00:00',time());
            $t_end = date('Y-m-d 23:59:59',time());
            $where_time[] = ['follow_createtime', 'between', [$t_start, $t_end]];
        }
        // 查询符合条件的数据数量
        $field = "count(id) as total,";
        $field .= "SUM(CASE WHEN tag_ids not like '%et2KBLHwAAoDbLHp-LazhmBIvafKbcsw%' THEN 1 ELSE 0 END) as speak_num,";
        $field .= "SUM(CASE WHEN tag_ids like '%et2KBLHwAA1Xn9Ro9vRsF2SI_L2NtyEg%' THEN 1 ELSE 0 END) as noentry_num,";
        $field .= "SUM(CASE WHEN tag_ids like '%et2KBLHwAAuIk1BowJ3Nr0O3WWOaGlWw%' THEN 1 ELSE 0 END) as noad_num,";
        $field .= "SUM(CASE WHEN tag_ids like '%et2KBLHwAAFabpSDesIpqrv6XVw9-j6A%' THEN 1 ELSE 0 END) as num_0,";
        $field .= "SUM(CASE WHEN tag_ids like '%et2KBLHwAAbaoBZzdEHwrW7wvX3r3ndg%' THEN 1 ELSE 0 END) as num_20,";
        $field .= "SUM(CASE WHEN tag_ids like '%et2KBLHwAA9N8vfqm4rcUsaxnOZ5PBAQ%' THEN 1 ELSE 0 END) as num_40,";
        $field .= "SUM(CASE WHEN tag_ids like '%et2KBLHwAABxKKZs1w8VhCH-pZPskn1Q%' THEN 1 ELSE 0 END) as num_60,";
        $field .= "SUM(CASE WHEN tag_ids like '%et2KBLHwAAIRSGz_PXmqZq_lQC6FIU1A%' THEN 1 ELSE 0 END) as num_80,";
        $field .= "SUM(CASE WHEN tag_ids like '%et2KBLHwAAoWwZWpe_yZ94_klPnjmipA%' THEN 1 ELSE 0 END) as num_100";
        $data = Db::name('wxk_customer')
            ->fieldRaw($field)
            ->where($where)
            ->where($where_time)
            ->group('follow_userid')
            ->column($field,'follow_userid');

        $j = [];
        foreach ($sales as $k => $v) {
            $j[$k]['date'] = '第一阶段';
            $j[$k]['username'] = $v['username'];
            $j[$k]['userid'] = $v['userid'];
            if(array_key_exists($v['userid'],$data)){
                $d = $data[$v['userid']];
                $j[$k]['total'] = (int)$d['total'];
                $j[$k]['speak_num'] = (int)$d['speak_num'];
                $j[$k]['speak_rate'] = number_format($d['speak_num'] / $d['total'], 2) * 100;
                $j[$k]['noentry_num'] = (int)$d['noentry_num'];
                $j[$k]['noad_num'] = (int)$d['noad_num'];
                $j[$k]['num_0'] = (int)$d['num_0'];
                $j[$k]['num_20'] = (int)$d['num_20'];
                $j[$k]['num_40'] = (int)$d['num_40'];
                $j[$k]['num_60'] = (int)$d['num_60'];
                $j[$k]['num_80'] = (int)$d['num_80'];
                $j[$k]['num_100'] = (int)$d['num_100'];
            }else{
                $j[$k]['total'] = (int)0;
                $j[$k]['speak_num'] = (int)0;
                $j[$k]['speak_rate'] = (int)0;
                $j[$k]['noentry_num'] = (int)0;
                $j[$k]['noad_num'] = (int)0;
                $j[$k]['num_0'] = (int)0;
                $j[$k]['num_20'] = (int)0;
                $j[$k]['num_40'] = (int)0;
                $j[$k]['num_60'] = (int)0;
                $j[$k]['num_80'] = (int)0;
                $j[$k]['num_100'] = (int)0;
            }

        }
        $t = Db::name('wxk_customer')
            ->fieldRaw($field)
            ->where($where_time)
            ->select()->toArray();
        $j[] = [
            'date' => '第一阶段',
            'username' => '盟硕',
            'userid' => '盟硕',
            'total' => (int)$t[0]['total'],
            'speak_num' => (int)$t[0]['speak_num'],
            'speak_rate' => $t[0]['total'] ? number_format($t[0]['speak_num'] / $t[0]['total'], 2) * 100 : 0,
            'noentry_num' => (int)$t[0]['noentry_num'],
            'noad_num' => (int)$t[0]['noad_num'],
            'num_0' => (int)$t[0]['num_0'],
            'num_20' => (int)$t[0]['num_20'],
            'num_40' => (int)$t[0]['num_40'],
            'num_60' => (int)$t[0]['num_60'],
            'num_80' => (int)$t[0]['num_80'],
            'num_100' => (int)$t[0]['num_100']
        ];
        response(200, '', $j);
    }
    /**
     * 内容列表
     * User: 李宁
     * */
    public function get_content_list_by_type(){
        $param = $this->param;
        $where = [];
        $type = $param['type'];
        if($type){
            $where[] = ['type','=',$type];
        }
        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['title|content','like','%'.$param['keyword'].'%'];
        }
        if(isset($param['industry']) && !empty($param['industry'])){
            $where[] = ['industry','=',$param['industry']];
        }
        $type_arr = [1=>'知识库',2=>'案例库',3=>'快捷消息'];
        $industry = [
            1 => '护肤彩妆',
            2 => '教育',
            3 => '旅游',
            4 => '大交通',
            5 => '房产',
            6 => '商务服务',
            7 => '本地生活',
            8 => '医疗',
            9 => '金融',
            10 => '摄影',
            11 => '海外保健品',
            12 => '招商加盟',
            13 => '家具',
            14 => '零售百货',
            15 => '家居',
            16 => '健康',
            17 => '文体娱乐'
        ];
        $list = Db::name('cms_content_engine')
            ->field('id,title,cover,industry,content,type,create_at')
            ->where($where)
            ->order('create_at' , 'desc')
            ->paginate($param['limit'])
            ->each(function ($item) use ($type_arr,$industry) {
                $item['type'] = $type_arr[$item['type']];
                $item['desc'] = mb_substr(strip_tags($item['content']),0,50,'utf-8');
                $item['industry'] = array_key_exists($item['industry'],$industry) ? $industry[$item['industry']] : '';
                unset($item['content']);
                return $item;
            })->toArray();

        response(200, '', $list['data'], $list['total']);
    }
    /**
     * 内容详情
     * User: 李宁
     * */
    public function new_content_detail()
    {
        $param = $this->param;
        $id = $param['id'];
        if(!$id){
            response(500, '缺少id');
        }
        $data = Db::name('cms_content_engine')
            ->field('id,title,cover,industry,content,type,create_at')
            ->where('id',$id)->find();

        response(200, '',$data);
    }
    /**
     * 添加内容
     * User: 李宁
     * */
    public function new_content_add()
    {
        $param = $this->param;
        if(!$param['type']){
            response(500, 'type不能为空');
        }
        if(!$param['title']){
            response(500, '标题不能为空');
        }
        $data = [
            'id' => uuid(),
            'type' => $param['type'],
            'title' => $param['title'],
            'cover' => $param['cover'],
            'content' => htmlspecialchars_decode($param['content'])
        ];
        if(isset($param['industry']) && !empty($param['industry'])){
            $data['industry'] = $param['industry'];
        }

        $id = Db::name('cms_content_engine')->insertGetId($data);
        if($id){
            response(200, '操作成功');
        }else{
            response(500, '操作失败');
        }
    }
    /**
     * 修改内容
     * User: 李宁
     * */
    public function new_content_edit()
    {
        $param = $this->param;
        $id = $param['id'];
        if(!$id){
            response(500, '缺少id');
        }
        if(!$param['title']){
            response(500, '标题不能为空');
        }
        $data = [
            'title' => $param['title'],
            'cover' => $param['cover'],
            'content' => htmlspecialchars_decode($param['content']),
            'update_at' => date('Y-m-d H:i:s',time())
        ];
        if(isset($param['industry']) && !empty($param['industry'])){
            $data['industry'] = $param['industry'];
        }

        $rows = Db::name('cms_content_engine')->where('id',$id)->update($data);
        if($id){
            response(200, '操作成功');
        }else{
            response(500, '操作失败');
        }
    }
    /**
     * @notes  上传图片
     */
    public function new_content_upload_images(){
        $time = date('YmdHis');
        if ($_FILES["file"]["error"]) {
            return rsp(500, $_FILES["file"]["error"]);
        }
        $end_name = strtoupper(mb_substr(strrchr($_FILES["file"]["name"], '.'), 1));
        if(($_FILES["file"]["type"] == "image/png" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "image/jpg") && $_FILES["file"]["size"] < 2048000) {
            $filename = './uploads/content/'.$time. '.jpg';
            $type = 'image';
        }else{
            return rsp(500, '此类型不支持上传');
        }
        $filename = iconv("UTF-8", "gb2312", $filename);
        move_uploaded_file($_FILES["file"]["tmp_name"], $filename);
        $url = \think\facade\Request::domain() . mb_substr($filename, 1);
        if($url){
            return rsp(200, '成功', ['content' => $url, 'file_name' => $_FILES['file']['name'], 'file_suffix' => $end_name]);
        }else{
            return rsp(500, '上传失败');
        }
    }
    /**
     * 删除内容
     * User: 李宁
     * */
    public function new_content_del(){
        $param = $this->param;
        $id = $param['id'];
        if(!$id){
            response(500, '缺少id');
        }
        $row = Db::name('cms_content_engine')->where('id','=',$id)->delete();
        if($row){
            response(200, '操作成功');
        }else{
            response(500, '操作失败');
        }
    }
    /**
     * 案例库分类
     * User: 李宁
     * */
    public function get_case_category(){
        $data = [
            1 => '护肤彩妆',
            2 => '教育',
            3 => '旅游',
            4 => '大交通',
            5 => '房产',
            6 => '商务服务',
            7 => '本地生活',
            8 => '医疗',
            9 => '金融',
            10 => '摄影',
            11 => '海外保健品',
            12 => '招商加盟',
            13 => '家具',
            14 => '零售百货',
            15 => '家居',
            16 => '健康',
            17 => '文体娱乐'
        ];
        response(200, '',$data);
    }


    //为原跟进表找到external_userid
    public function get_external_userid_for_followup(){
//        $followup = Db::name('t_followup')->alias('fu')
//            ->field('fu.*,l.external_userid,l.follow_user_userid as luserid')
//            ->leftJoin('t_leads l', 'l.id = fu.leads_id')
//            ->order('fu.leads_id asc')
//            ->select()->toArray();
//        $data = [];
//        foreach ($followup as $k => $v){
//            Db::name('t_followup')->where('id',$v['id'])->update(['external_userid' => $v['external_userid']]);
//        }
    }
    //跟进数据迁移至新表
    public function followup_to_f(){
//        $followup = Db::name('t_followup')->alias('fu')
//            ->field('fu.*,ue.external_userid as e_uid,ue.new_external_userid as neu_id')
//            ->leftJoin('userid_extend ue', 'ue.new_external_userid = fu.external_userid')
//            ->order('fu.leads_id asc')
//            ->select()->toArray();
//
//        $sales = [
//            'woBxtoNQAAwiMMitb9yTrUdDz48AFjEw' => 'wangshuo',
//            'woBxtoNQAADllxuWcQtvNhehMQ3DL9mg' => 'zhangguoqing',
//            'woBxtoNQAAaBN-vhfhKabm88TW4tLR1A' => 'huayunlong',
//            'woBxtoNQAArzKSeoMxOLUU8S6y_7Wbmw' => 'pbl',
//            'woBxtoNQAACUz90fAeubMzJqOA5tpXHw' => 'admin'
//        ];
//        $admin = [
//            'woBxtoNQAAwiMMitb9yTrUdDz48AFjEw' => 'fffc607e-88bc-5526-7da3-5a767e94e573',
//            'woBxtoNQAADllxuWcQtvNhehMQ3DL9mg' => '63b5a7b6-b696-7c94-cded-e2043559138d',
//            'woBxtoNQAAaBN-vhfhKabm88TW4tLR1A' => '270f275a-d730-549f-f7ad-fda96e50a341',
//            'woBxtoNQAArzKSeoMxOLUU8S6y_7Wbmw' => 'pbl',
//            'woBxtoNQAACUz90fAeubMzJqOA5tpXHw' => 'admin'
//        ];
//        $data = [];
//        $empty = '';
//        foreach ($followup as $k => $v){
//            if($v['e_uid']){
//                $data['id'] = uuid();
//                $data['external_user_id'] = $v['e_uid'];
//                //$data['neu_id'] = $v['neu_id'];
//                $data['follow_userid'] = $sales[$v['userid']];
//                $data['user_type'] = 1;
//                $data['add_follow_user'] = $admin[$v['userid']];
//                $data['follow_type'] = 2;
//                $data['content'] = $v['followup_notes'];
//                $data['create_at'] = date("Y-m-d H:i:s",$v['create_time']);
//                $data['update_at'] = date("Y-m-d H:i:s",$v['create_time']);
//                Db::name('wxk_customer_follow')->insert($data);
//            }else{
//                $empty .= $v['leads_id'].',';
//            }
//        }
//        echo $empty;
    }
    //客户资料迁移至画像表
    public function leads_to_p(){
//        $leads = Db::name('t_leads')->alias('l')
//            ->field('l.*,ue.external_userid as e_uid')
//            ->leftJoin('userid_extend ue', 'ue.new_external_userid = l.external_userid')
//            ->where('l.follow_user_remark_mobiles','<>','')
//            ->whereOr('l.industry_level_one','<>','')
//            ->whereOr('l.industry_level_two','<>','')
//            ->whereOr('l.province','<>','')
//            ->whereOr('l.area','<>','')
//            ->order('l.id asc')
//            ->select()->toArray();
//
//        $ins = Db::name('wxk_customer_industry')->column('name','id');
//        $data = [];
//        $empty = '';
//        foreach ($leads as $k => $v){
//            if($v['e_uid']){
//                $data['id'] = uuid();
//                $data['external_user_id'] = $v['e_uid'];
//                $data['follow_remark_mobiles'] = $v['follow_user_remark_mobiles'];
//                if($v['industry_level_one']){
//                    $data['industry'] = $ins[$v['industry_level_one']].'/'.$ins[$v['industry_level_two']];
//                }
//                if($v['province']){
//                    $data['area'] = $v['province'].'/'.$v['area'];
//                }
//                $count = Db::name('wxk_customer_portrait')->where('external_user_id',$v['e_uid'])->find();
//                if($count){
//                    unset($data['id']);
//                    unset($data['external_user_id']);
//                    Db::name('wxk_customer_portrait')->update($data);
//                }else{
//                    Db::name('wxk_customer_portrait')->insert($data);
//                }
//            }else{
//                $empty .= $v['id'].',';
//            }
//        }
//        echo $empty;
    }
}